<?php

namespace App\Http\Middleware;

use App\Library\Logic\ShopUserLogic;
use Closure;
use Exception;
use Illuminate\Http\Request;

class VerifyToken
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     * @throws Exception
     */
    public function handle(Request $request, Closure $next): mixed
    {
        $userId = userId();
        if ($userId === 0) return fail(430);
        $shopUser = ShopUserLogic::detail($userId, ['userMainId', 'userPeerPower', 'isSystem', 'agent', 'userStatus']);
        if (is_null($shopUser)) return fail(430);
        else if ($shopUser->user_status === 2) return fail(405);
        define('USERID', $userId);
        define('MAINID', $shopUser->user_main_id === 0 ? $userId : $shopUser->user_main_id);
        define('POWER', 1);
//        define('POWER', (int)($shopUser->user_peer_power === 1));
        define('SYSTEM', $shopUser->is_system);
        define('AGENT', $shopUser->agent);
        return $next($request);
    }
}
